import React, { memo, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Select,
  Row,
  Col
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import store from '@/pages/home/store';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch,
  repoNameId
} from './config';
import { action3, action4, action5, action6 } from '@/pages/home/createAction';
import { openNotification } from '@/components/Pop';
const { Option } = Select;
//Form-产品名称
const productName = (dataArray: any) => {
  let TypeArr: any = [];
  // eslint-disable-next-line array-callback-return
  dataArray.map((i: { productName: string }) => {
    TypeArr.push(i.productName);
  });
  return (
    <Form.Item
      label="产品(材料)名称"
      name="productName"
      rules={[{ required: true, message: '请选择产品名称' }]}
    >
      <Select
        disabled={store.getState().name === '编辑' ? true : false}
        defaultValue={''}
        onChange={(value, records: any) => {
          let productId = records.key;
          store.dispatch(action6(productId));
        }}
      >
        {dataArray.map((i: { productName: string; id: string }) => {
          return (
            <Option value={i.productName} key={i.id} children={null}></Option>
          );
        })}
      </Select>
    </Form.Item>
  );
};
//Form-小库id
const repoSeleted = (dataArray: [], newref: any) => {
  //仓库id是根据文档的入库id，与产品id无关，如有增删这里需要更改
  let repoOtions: string[] = [];
  // eslint-disable-next-line array-callback-return
  dataArray.map((i: { repoType: string }) => {
    switch (i.repoType) {
      case '辅料仓库': {
        repoOtions = ['辅料仓库1', '辅料仓库2', '辅料仓库3'];
        break;
      }
      case '肉鸡速冻库': {
        repoOtions = ['肉鸡速冻库1', '肉鸡速冻库2', '肉鸡速冻库3'];
        break;
      }
      case '肉鸡冷藏库': {
        repoOtions = ['肉鸡冷藏库1', '肉鸡冷藏库2', '肉鸡冷藏库3'];
        break;
      }
    }
  });
  //利用选择的仓库名去获取目前的数量
  const getUpper = (repoName: string) => {
    http.get(`/server/repositoryInfoSlaughter/getUpperLimitList`).then((res) => {
      // eslint-disable-next-line array-callback-return
      const getUpper = res.data.filter((i: any) => {
        return i.repositoryName === repoName
      }
      )
      const { quantity, upperLimit } = getUpper[0];
      newref.current.setFieldsValue({
        getStore: quantity,
        getUpper: upperLimit
      })
    })
  }
  return (
    <Form.Item
      label="选择具体仓库"
      name="repoName"
      rules={[{ required: true, message: '请选择具体仓库' }]}
    >
      <Select
        defaultValue={''}
        //当新增入库时不禁用仓库选择，当编辑时禁用
        disabled={store.getState().name === '编辑' ? true : false}
        onSelect={(e: string) => getUpper(e)}
      >
        {repoOtions.map((i) => {
          return <Option value={`${i}`} key={i} children={null}></Option>;
        })}
      </Select>
    </Form.Item>
  );
};
//form
// 订单编号，客户名 创建时间  件数 只数 重量 提货日期 提货人
// customerName numberOfPieces only weight averageWeight pickupDate pickupPerson species remark
const NewForm = (props: any) => {
  const Options = [
    {
      label: '辅料仓库',
      value: '1'
    },
    { label: '肉鸡速冻库', value: '2' },
    { label: '肉鸡冷藏库', value: '3' }
  ];
  const [dataArray, setDataArray]: any = useState([]);
  return (
    <Form ref={props.newref} layout={'vertical'} style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row >
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>

          <Form.Item
            label="仓库类型"
            name="repoType"
            rules={[{ required: true, message: '请选择仓库类型' }]}
          >
            <Select
              disabled={store.getState().name === '编辑' ? true : false}
              onChange={(value) => {
                //当发生该变的时候，通过表单去清空已选择的框value
                props.newref.current.setFieldsValue({
                  productName: '',
                  repoSeleted: ''
                });
                store.dispatch(action5(value));
                setDataArray(
                  props.searchid.filter(
                    (item: any) => item.repoType === store.getState().name
                  )
                );
              }}
            >
              {Options.map((i) => (
                <Option value={i.label} key={i.value} children={null}></Option>
              ))}
            </Select>
          </Form.Item>
          {repoSeleted(dataArray, props.newref)}
          {productName(dataArray)}
          <Form.Item
            name="getStore"
            label="该仓库库存容量"

          >
            <Input disabled></Input>
          </Form.Item>
          <Form.Item
            name="getUpper"
            label="该仓库现库存量"

          >
            <Input disabled></Input>
          </Form.Item>

        </Col>
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>
          <Form.Item
            name="grade"
            label="请输入等级"
            rules={[{ required: true, message: '请选择等级' }]}
          >
            <Select>
              <Option value="A">A</Option>
              <Option value="B">B</Option>
              <Option value="C">C</Option>
              <Option value="不合格">不合格</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="weight"
            label="请输入重量"
            rules={[{ required: true, message: '请输入重量' }]}
          >
            <Input></Input>
          </Form.Item>

          <Form.Item
            name="money"
            label="请输入单价"
            rules={[{ required: true, message: '请输入单价' }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            name="supplier"
            label="请输入供应商"
            rules={[{ required: true, message: '请输入供应商' }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            name="quantity"
            label="请选择数量（个）"
            rules={[{ required: true, message: '请选择数量' }]}
          >
            <Select>
              <Option value={100}>100</Option>
              <Option value={200}>200</Option>
              <Option value={500}>500</Option>
              <Option value={1000}>1000</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增入库
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkit();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>


    </div>
  );
};

const Instore = memo(() => {
  //入库的选择大库
  const [searchid, setsearchid]: any = useState([]);
  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //是否新增
  const [editId, setEditId] = useState<number>();
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);

  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    http.get('/server/inSlaughter/list/1/10').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);
  //获取当前时间
  let time = () => {
    var d = new Date();
    const date = d.getDate();
    const year = d.getUTCFullYear();
    const hours = d.getHours();
    const month = d.getMonth() + 1;
    const minutes = d.getMinutes();

    const a = [year, month, date].join('-');
    const b = [hours, minutes].join(':');
    return [a, b].join(' ');
  };
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };
  //批量删除/server/feeVoucherSlaughter/deletion/batch
  // /server/feeVoucherSlaughter/list/{pageNum}/{pageSize}
  const checkit = () => {
    http({
      url: `/server/inSlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify([]),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/server/inSlaughter/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };
  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  // 对话框确认--入库或者修改数据
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改 /server/feeVoucherSlaughter/update/{id}
    if (store.getState().name === '编辑') {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/server/inSlaughter/update/${editId}`, {
          ...newedited
        })
        .then(() => {
          // 再请求一次获得修改后的数据
          http.get('/server/inSlaughter/list/1/10').then((res) => {
            setdataSource(res.data.records);
          });
        });

      return;
    }

    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      productName,
      supplier,
      money,
      quantity,
      weight,
      repoName,
      grade
    } = addData;
    http
      .post('/server/inSlaughter/save', {
        specification: repoName,
        productName,
        supplier,
        money: Number(money),
        quantity: Number(quantity),
        weight: Number(weight),
        repoId: Number(repoNameId[repoName]),
        productId: Number(store.getState().key),
        grade,
        date: time()
      })
      .then(() => {
        // setdataSource([...dataSource, ax])
        http.get('/server/inSlaughter/list/1/10').then((res) => {
          setdataSource(res.data.records);
        });
      });
    http.get('/server/repositoryInfoSlaughter/list/1/20').then((res) => {
      // eslint-disable-next-line array-callback-return
      const isOver = res.data.records.some((item: any) => {
        return item.id === repoNameId[repoName] && item.quantity + quantity > item.upperLimit;
      });
      if (isOver) {
        openNotification('top', '仓库已满！请选择其他仓库');
        return;
      }
      openNotification('top', '入库成功！')
      setAddModalVisible(false);
    });
  };
  //编辑
  const edit = (item: any) => {
    setAddModalVisible(true);
    //这里不能单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...item
      });
      store.dispatch(action3('编辑'));
      setEditId(item.id);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    store.dispatch(action4('新增'));

    setTimeout(() => {
      newref.current.setFieldsValue({
        userId: '',
        productName: '',
        matName: '',
        repoType: '',
        repoId: '',
        repoName: '',
        supplier: '',
        productId: '',
        money: '',
        cases: '',
        quantity: '',
        weight: '',
        getStore: '',
        getUpper: '',
      });
    }, 0);
    setAddModalVisible(true);

    http.get('/server/productionSlaughter/list/1/30').then((res) => {
      //console.log(res.data.records)
      setsearchid(res.data.records);
    });
  };

  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //自定义每页显示项目的选项
      pageSizeOptions: ['1', '2', '3', '4', '5', '6', '8', '10'],
      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length
    }
  };

  // customerName numberOfPieces only weight averageWeight pickupDate pickupPerson species remark
  const FormColumns: any = [
    {
      title: '产品（材料）名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 150
    },

    {
      title: '入库号码',
      dataIndex: 'repoId',
      key: 'repoId',
      width: 150
    },
    {
      title: '入库数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 150
    },
    {
      title: '货品重量',
      dataIndex: 'weight',
      key: 'weight',
      width: 150
    },
    {
      title: '单价',
      dataIndex: 'money',
      key: 'money',
      width: 150
    },
    {
      title: '供应商',
      dataIndex: 'supplier',
      key: 'supplier',
      width: 150
    },
    {
      title: '签收单位',
      dataIndex: 'unit',
      key: 'unit',
      width: 150
    },

    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => {
              http
                .delete(`/server/inSlaughter/delete/${record.id}`)
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid*/}
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={() => {

                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索 条件查询 /server/feeVoucherSlaughter/get

  const onFinish = (form: any) => {
    // 发送请求
    http.post('/server/inSlaughter/get', form).then((res: any) => {
      if (res.statusCode !== 20000) {
        return message.error('查询失败');
      }
      const data = res.data || [];
      setdataSource(data);
    });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http.get(`/server/inSlaughter/get/${data.id}`).then((res) => {
      setDrawerid(res.data);
    });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  const pieRef = useRef<HTMLDivElement | HTMLElement | object | any>(null);
  const renderPie = () => {
    setTimeout(() => {
      echarts.init(pieRef.current);
      type EChartsOption = echarts.EChartsOption;
      var chartDom = document.getElementById('pie')!;
      var myChart = echarts.init(chartDom);
      var option: EChartsOption;

      option = {
        title: {
          text: '速冻库出库管理',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '速冻库的出库管理',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 100, name: '冷冻鸡爪' },
              { value: 100, name: '冷冻鸡腿' },
              { value: 200, name: '冷冻鸡胸' },
              { value: 300, name: '冷冻鸡翅' },
              { value: 500, name: '冷冻整鸡' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      option && myChart.setOption(option);
    }, 0);
  };
  return (
    <DivWrapper>
      {searchMore ? (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      ) : null}
      <Buttongroup
        checkit={() => checkit()}
        add={() => add()}
        exported={() => exported()}
      ></Buttongroup>
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      ></UseSearch>
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
        style={{ float: 'right' }}
      ></SearchSelector>

      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
        ></Table>

        <div
          ref={pieRef}
          id="pie"
          style={{
            height: '400px',
            marginTop: '50px',
            width: '100%'
          }}
        >
          速冻库的出库管理如下：
          {renderPie()}
        </div>

      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        {/* 订单编号，客户名 创建时间  件数 只数 重量 提货日期 提货人 */}
        <Descriptions
          title={'入库记录详情'}
          bordered
          style={{ width: '450px' }}
        >
          <Descriptions.Item label="仓库编号">

            {Drawerid.repoId}
          </Descriptions.Item>
          <Descriptions.Item label="产品名称">
            {Drawerid.productName}
          </Descriptions.Item>
          <Descriptions.Item label="收货商">
            {Drawerid.supplier}
          </Descriptions.Item>
          <Descriptions.Item label="单价">
            {Drawerid.money}
          </Descriptions.Item>
          <Descriptions.Item label="产品编号">
            {Drawerid.productId}
          </Descriptions.Item>
          <Descriptions.Item label="等级">
            {Drawerid.grade}
          </Descriptions.Item>
          <Descriptions.Item label="数量">
            {Drawerid.quantity}
            {/*  supplier,
        money: Number(money),
        quantity: Number(quantity),
        weight: Number(weight),
        repoId: Number(repoNameId[repoName]),
        productId: Number(store.getState().key),
        grade,
        date: time()*/ }
          </Descriptions.Item>
          <Descriptions.Item label="重量">{Drawerid.weight}</Descriptions.Item>
          <Descriptions.Item label="入库时间">
            {Drawerid.date}
          </Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse',

        }}
        title="新增入库"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} searchid={searchid}></NewForm>
      </Modal>
    </DivWrapper>
  );
});
export default Instore;
